#include "service.h"
#include <pistache/http_header.h>
#include <pistache/http_headers.h>
#include <cstdio>

Service::Service() {
    mSearch = new Search();
}

Service::~Service() {
    delete mSearch;
    mSearch = nullptr;
}

void Service::TestGet(const Rest::Request & request, Http::ResponseWriter response) {
    response.headers().add<Http::Header::ContentType>(MIME(Application, Json));
    response.send(Http::Code::Ok, "{\"greeting\":\"hello\", \"number\":2 }");
}

void Service::TestPost(const Rest::Request & request, Http::ResponseWriter response) {
    response.headers().add<Http::Header::ContentType>(MIME(Application, Json));
    printf("%s\n", request.body().c_str());
    response.send(Http::Code::Ok, "{\"result\":666}");
}

void Service::IndexPage(const Rest::Request & request, Http::ResponseWriter response) {
    Http::serveFile(response, "front_end/index.html");
}

void Service::NextMove(const Rest::Request & request, Http::ResponseWriter response) {
    /* 格式转换 */
    const std::string & s = request.body();
    int i;
    int step = 0;
    int n = s.length();
    for (i = 0; i < n; i++) {
        if (s[i] < '0' || s[i] > '9') {
            break;
        }
        step = step * 10 + (s[i] - '0');
    }
    int maxLevel = 0;
    for (i++; i < n; i++) {
        if (s[i] < '0' || s[i] > '9') {
            break;
        }
        maxLevel = maxLevel * 10 + (s[i] - '0');
    }
    Positions positions;
    std::unordered_map<char, int> repeatedTimes;
    int piece;
    for (; s[i] != '.'; i += 3) {
        piece = (int)s[i] | (repeatedTimes[s[i]] << 8);
        repeatedTimes[s[i]]++;
        positions[piece] = (Coordinate){s[i + 1] - '0', s[i + 2] - '0'};
    }

    /* 把转换后的数据输入模型 */
    mSearch->SetMaxLevel(maxLevel);
    Solution sol = mSearch->SearchNextMove(step, positions);

    response.headers().add<Http::Header::ContentType>(MIME(Application, Json));
    static char msg[72];
    sprintf(msg, "{\"x0\":%d,\"y0\":%d, \"x1\":%d,\"y1\":%d}", sol.from.x, sol.from.y, sol.to.x, sol.to.y);
    response.send(Http::Code::Ok, (char*)msg);
}
